import {
  LOGIN_START,
  LOGIN_SUCCESS,
  LOGIN_FAIL
} from '../action/actionTypes'
import produce from 'immer'
import store from 'store2'
let initUser = {
  isLogin:false,
  isLoading:false,
  userInfo:null
}

// 尝试提取本地存储用户信息
let info = store.get('userInfo') || store.session('userInfo')
if(info){
  initUser.isLogin = true
  initUser.userInfo = info
}

export default function user(state=initUser,action){
  switch (action.type) {
    case LOGIN_START:  //开始登录
      let obj = produce(state,(draft)=>{ //draft可以认为是state原数据包的一个拷贝
        draft.isLoading = true
      })
      console.log('开始登录',obj);
      return obj
    case LOGIN_SUCCESS:  //登录成功
      // 本地存储用户信息（localStorage、第三方store2）
      let {payload,remember} = action
      if(remember){  //记住密码
        store.set('userInfo',payload)  //本地存储
      }else{
        store.session('userInfo',payload)
      }
      return produce(state,(draft)=>{
        draft.isLogin = true
        draft.isLoading = false
        draft.userInfo = payload  //此处的payload包含的是后端下发的用户信息
      })
    case LOGIN_FAIL:    //登录失败、退出登录
      store.remove('userInfo')
      store.session('userInfo','')
      return produce(state,(draft)=>{
        draft.isLogin = false
        draft.isLoading = false
        draft.userInfo = null
      })
    default:
      return state
  }
}